package com.yf.thumbbackend.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yf.thumbbackend.entity.Thumb;
import com.yf.thumbbackend.entity.enums.ThumbEnums;
import com.yf.thumbbackend.mapper.BlogMapper;
import com.yf.thumbbackend.service.BlogService;
import com.yf.thumbbackend.service.ThumbService;
import com.yf.thumbbackend.util.RedisKeyUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 随风
 * @date 2025/4/20 11:56
 * @description SyncThumb2DBJob
 */
@Component
@Slf4j
public class SyncThumb2DBJob {

    @Resource
    private BlogService blogService;
    @Resource
    private ThumbService thumbService;
    @Resource
    private BlogMapper blogMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Scheduled(initialDelay = 10000,fixedDelay = 10000)
    @Transactional(rollbackFor = Exception.class)
    public void run(){

        log.info("定时任务开始执行");
        DateTime nowDate = DateUtil.date();
        String date = DateUtil.format(nowDate, "HH:mm:") + (DateUtil.second(nowDate) / 10 - 1) * 10;
        syncThumb2DBByDate(date);
        log.info("临时数据同步完成");

    }

    public void syncThumb2DBByDate(String date){
        //获取临时点赞 和取消点赞数据
        String tempThumbKey = RedisKeyUtil.getTempThumbKey(date);
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(tempThumbKey);
        boolean thumbMapEmpty = CollUtil.isEmpty(entries);

        //同步点赞
        //首先同步thumb
        //构建传参列表
        HashMap<Long, Long> countMap = new HashMap<>();
        if (thumbMapEmpty){
            return;
        }
        ArrayList<Thumb> thumbs = new ArrayList<>();
        LambdaQueryWrapper<Thumb> queryWrapper = new LambdaQueryWrapper<>();
        boolean needRemove = false;

        //遍历entries，获取userId和blogId
        for (Object userIdBlogId :entries.keySet()){
            String[] split = userIdBlogId.toString().split(":");
            Long userId = Long.valueOf(split[0]);
            Long blogId = Long.valueOf(split[1]);
            // -1 取消点赞 1 点赞
            Integer thumbType = Integer.valueOf(entries.get(userIdBlogId).toString());
            if(thumbType == ThumbEnums.INCR.getCode()){
                //如果thumbType为1，则创建Thumb对象，并添加到thumbs列表中
                Thumb thumb = new Thumb();
                thumb.setBlogId(blogId);
                thumb.setUserId(userId);
                thumbs.add(thumb);
            }else if(thumbType == ThumbEnums.DECR.getCode()){
                //如果thumbType为-1，则设置needRemove为true，并构建查询条件
                needRemove = true;
                queryWrapper.or().eq(Thumb::getUserId, userId).eq(Thumb::getBlogId,blogId);

            }else {
                //如果thumbType不为1或-1，则打印警告日志，并跳过此次循环
                if (thumbType!=ThumbEnums.NON.getCode()){
                    log.warn("数据异常：{}",userId+","+blogId+ ","+thumbType);
                }
                continue;
            }
            //计算点赞增量
            countMap.put(blogId,countMap.getOrDefault(blogId,0L)+thumbType);

        }
        //批量插入
        thumbService.saveBatch(thumbs);
        //批量删除
        if (needRemove){
            thumbService.remove(queryWrapper);
        }
        //批量更新点赞数
        if (!countMap.isEmpty()){
            blogMapper.bathUpdateThumbCount(countMap);
        }
        //异步删除
        Thread.startVirtualThread(() -> {
            redisTemplate.delete(tempThumbKey);
        });


    }
}
